const express = require('express')
const { query } = require('../utils/pool')
const router = express.Router()
// 疾病添加
router.post('/add', async (req, res, next) => {
  const obj = req.body
  obj.ctime = Date.now()
  try {
    var result = await query('insert into ih_disease set ?', [obj])
  } catch (err) {
    return next(err)
  }
  console.log(result)
  res.send({ code: 200, msg: '疾病添加成功' })
})
// 疾病列表
router.get('/list', async (req, res, next) => {
  const obj = req.query
  if (!obj.pno) obj.pno = 1;
  if (!obj.count) obj.count = 10;
  const size = parseInt(obj.count);
  const start = (obj.pno - 1) * size;
  try {
    let sql
    if (obj.title) {
      sql = `select * from ih_disease where title like '%${obj.title}%' order by did desc limit ?,?;select count(*) as n from ih_disease where title like '%${obj.title}%'`
    } else {
      sql = 'select * from ih_disease order by did desc limit ?,?;select count(*) as n from ih_disease'
    }
    var result = await query(sql, [start, size])
  } catch (err) {
    return next(err)
  }
  console.log(result)
  res.send({
    code: 200,
    msg: '文章列表',
    data: result[0],
    total: result[1][0].n,
    pno: obj.pno
  })
})
// 疾病修改
router.put('/update', async (req, res, next) => {
  const obj = req.body
  try {
    var result = await query('update ih_disease set ? where did=?', [obj, obj.did])
  } catch (err) {
    return next(err)
  }
  if (result.changedRows === 0) {
    res.send({ code: 400, msg: '修改失败' })
  } else {
    res.send({ code: 200, msg: '修改成功' })
  }
})
// 删除疾病
router.delete('/', async (req, res, next) => {
  const { did } = req.query
  try {
    var result = await query('delete from ih_disease where did=?', [did])
  } catch (err) {
    return next(err)
  }
  if (result.affectedRows === 0) {
    res.send({ code: 400, msg: '删除失败' })
  } else {
    res.send({ code: 200, msg: '删除成功' })
  }
})
module.exports = router